package com.aracky.common.config;

import com.aracky.common.util.UserIPUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author zengzhiping
 * @ClassName: MyMetaObjectHandler
 * @Description: 重写mybatisplus中的字段填充器  ---mybatisplus起始版本 3.3.0(推荐使用)
 * @date 2022年05月12日
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private Logger logger = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("start insert fill ....");
        //新增时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());

        if (UserIPUtil.getUserIsLoginIn()) {
            //新增创建人
            this.strictInsertFill(metaObject, "createBy", () -> String.valueOf(UserIPUtil.getCurrentUserId()), String.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("start update fill ....");
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        if (UserIPUtil.getUserIsLoginIn()) {
            //新增更新人
            this.strictUpdateFill(metaObject, "updateBy", () -> String.valueOf(UserIPUtil.getCurrentUserId()), String.class);
        }
    }

}
